﻿/*
 *接收用Socket 
 * 
 */
using System;
using System.Net;
using System.Net.Sockets;

namespace BusStationClient
{
    public class UdpReceiveSocket
    {
        /// <summary>
        /// 接收用Socket;
        /// </summary>
        private readonly Socket _receiveSocket;

        private readonly SocketAsyncEventArgs _receiveSocketArgs;

        private readonly IPEndPoint _localEndPoint;

        private readonly byte[] _receivebuffer;
        /// <summary>
        /// 接收到数据包时触发
        /// </summary>
        public event EventHandler<SocketAsyncEventArgs> OnDataReceived;



        /// <summary>
        /// 初始化Socket 和 地址。
        /// </summary>
        /// <param name="port">端口</param>
        public UdpReceiveSocket(int port)
        {
            _receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _localEndPoint = new IPEndPoint(IPAddress.Any, port);
            _receiveSocket.Bind(_localEndPoint);

            _receivebuffer = new byte[8000];
            _receiveSocketArgs = new SocketAsyncEventArgs { RemoteEndPoint = _localEndPoint };
            _receiveSocketArgs.Completed += receiveSocketArgs_Completed;
            _receiveSocketArgs.SetBuffer(_receivebuffer, 0, _receivebuffer.Length);

        }



        /// <summary>
        /// 开始接收数据
        /// </summary>
        public void StartReceive()
        {
            if (!_receiveSocket.ReceiveFromAsync(_receiveSocketArgs))
            {
                ProcessReceived(_receiveSocketArgs);
            }

        }


        void receiveSocketArgs_Completed(object sender, SocketAsyncEventArgs e)
        {
            switch (e.LastOperation)
            {
                case SocketAsyncOperation.ReceiveFrom:
                    this.ProcessReceived(e);
                    break;
                default:
                    throw new ArgumentException("The last operation completed on the socket was not a receive");
            }
        }

        /// <summary>
        /// 接收完成时处理请求。
        /// </summary>
        /// <param name="e"></param>
        void ProcessReceived(SocketAsyncEventArgs e)
        {
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                if (OnDataReceived != null)
                {
                        //不要进行耗时操作
                        OnDataReceived(_receiveSocket, e);
                }
            }
            StartReceive();

        }


        public void SendData(byte[] data, IPEndPoint ipEndPoint)
        {
            _receiveSocket.SendTo(data, ipEndPoint);
        }




    }
}
